import { useEffect } from "react";
import { Form, Input, Button, MessagePlugin } from "tdesign-react";
import { DesktopIcon, LockOnIcon } from "tdesign-icons-react";
import type { FormProps } from "tdesign-react";
import "./index.scss"
import { useNavigate } from "react-router-dom";
import { HAuthLogin } from "./api";
import { LoginResult, Tenant } from "./api/api.interface";

const LoginComponent = () => {
  const navigate = useNavigate();

  /**
   * 提交登录
   * @param e |
   * @returns 
   */
  const onSubmit: FormProps["onSubmit"] = async (e) => {
    if (e.validateResult === true) {
      HAuthLogin.userLogin<LoginResult>('用户登录', {
        userName: e.fields.account,
        password: e.fields.password
      }).then(data => {
        HAuthLogin.queryTenants<Tenant[]>('查询租户列表').then(tenants => {
          MessagePlugin.success("提交成功");
          setTenant(tenants);
          setTimeout(() => {
            navigate('/dashboard', { replace: true });
          }, 1000);
          localStorage.setItem('app.access_token', data.access_token);
          localStorage.setItem('app.account', JSON.stringify(data));
        }).catch(() => {
          MessagePlugin.error('登录失败');
        })
      }).catch(() => {
        MessagePlugin.error('登录失败');
      })
    }
  };

  /**
   * 设置租户
   */
  const setTenant = (tenants: Tenant[]) => {
    const localTenant = localStorage.getItem('app.tenant');
    if (!localTenant) {
      if (tenants.length > 0) {
        const [tenant] = tenants;
        localStorage.setItem('app.tenant', tenant.id);
      }
      return;
    }

    // 如果存在，需要检查一下是否在本地登录的租户中
    const checkResult = tenants.findIndex(t => t.id === localTenant);
    if (checkResult === -1) {
      const [tenant] = tenants;
        localStorage.setItem('app.tenant', tenant.id);
    }
  }

  const onReset: FormProps["onReset"] = (e) => {
    console.log(e);
    MessagePlugin.info("重置成功");
  };

  return (
    <div className="system-login__container">
      <div className="login-content__box">
        <h3 className="login-content__title">欢迎登录</h3>
        <Form statusIcon={true} onSubmit={onSubmit} onReset={onReset} colon={true} labelWidth={0}>
          <Form.FormItem name="account">
            <Input clearable={true} prefixIcon={<DesktopIcon />} placeholder="请输入账户名" />
          </Form.FormItem>
          <Form.FormItem name="password">
            <Input type="password" prefixIcon={<LockOnIcon />} clearable={true} placeholder="请输入密码" />
          </Form.FormItem>
          <Form.FormItem>
            <Button theme="primary" type="submit" block>
              登录
            </Button>
          </Form.FormItem>
        </Form>
      </div>
    </div>
  );
};

export default LoginComponent;
